package com.JingYan.filter;


import com.JingYan.util.StringUtils;
import com.JingYan.util.http.HttpHelper;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 可重复读请求 过滤器
 * 
 * @author ino
 */
@Slf4j
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {

        try {
            if (request instanceof HttpServletRequest){
                HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                String method = httpServletRequest.getMethod();
                //其他请求需要构建重复流的时候才能截取,不然会吃掉数据
                if (method == null || method.matches("GET") || method.matches("DELETE")) {
                    String contextPath = httpServletRequest.getContextPath();
                    String servletPath = httpServletRequest.getServletPath();
                    String requestUri = httpServletRequest.getRequestURI();
                    // 去掉 contextPath 和 servletPath
                    String remainingPath = requestUri.substring(contextPath.length());
                    remainingPath = remainingPath.substring(servletPath.length());
                    // 打印处理后的请求URI
                    log.info("处理后的请求地址: " + remainingPath);
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    log.info("请求传入参数: "+ JSON.toJSONString(parameterMap));
                }
            }
        } catch (Exception e) {
            log.error("参数拦截出错 {} ",e.getMessage());
        }
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest
                && StringUtils.equalsAnyIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE))
        {
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        if (null == requestWrapper)
        {
            chain.doFilter(request, response);
        }
        else
        {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy()
    {

    }
}
